import { NewBingServer } from "./server/index.js";
import { NewBingSocket, sendConversationMessage } from "./socket/index.js";
import { config } from "./config.js";
import ProxyAgent from "proxy-agent";
import { parentPort } from "worker_threads";
const { proxyUrl } = config;
const agent = ProxyAgent(proxyUrl);
const bingServer = new NewBingServer({
    agent
});
const bingSocket = new NewBingSocket({
    address: "/sydney/ChatHub",
    options: {
        agent
    }
});
let invocationId = -1;
let bingInfo;
const startBingConversation = async () => {
    initEvent();
    await initBingServer();
    initBingSocket();
};
const initEvent = () => {
    bingServer.on("new-bing:server:error", (...args) => { throw new Error(...args); });
    bingSocket.on("new-bing:socket:error", (...args) => { throw new Error(...args); });
    parentPort.on("message", (res) => {
        const { type } = res;
        if (type === "sendMessage") {
            sendConversationMessage.call(bingSocket, { message: res.message, invocationId: ++invocationId });
        }
    });
};
const initBingServer = async () => {
    await bingServer.reset();
    bingInfo = bingServer.bingInfo;
};
const initBingSocket = () => {
    bingSocket.mixBingInfo(bingInfo).createWs().initEvent().on("init:finish", () => {
        parentPort.postMessage({
            type: "init:finish"
        });
    }).on("message:finish", (data = "") => {
        parentPort.postMessage({
            type: "message:finish",
            data
        });
    }).on("message:ing", (data = "") => {
        parentPort.postMessage({
            type: "message:ing",
            data
        });
    });
};
startBingConversation();
